'use strict';

const Service = require('egg').Service;

class Tool extends Service {
    
    
    async getHoliday(day){
        const { ctx } = this;

        let apiRoute = "http://timor.tech/api/holiday/info/" + day;

        let data = await ctx.curl(apiRoute, {
            method: "GET",
            dataType: "json"
        })

        return data.data;
    }


    // 获取节假日列表
    async getHolidayList(start, end){
        const { ctx } = this;
        let Op = this.app.Sequelize.Op;

        let list = await ctx.model.Holiday.findAll({
            where: {
                timestamp: {
                    [Op.between]: [start, end]
                },
            }
        });

        return list;
    }


    async initDbHoliday(start, end){
        const { ctx } = this;
        

        while(start < end){
            let day = ctx.helper.msFormatTime("YYYY-MM-DD", start);
            console.log(day);

            let info = await this.getHoliday(day);

            //0工作日 3日前后补班
            if(info.type.type != 0 && info.type.type != 3){
                console.log(info);
                //查询更新
                let holiday = await ctx.model.Holiday.findOrCreate({
                    where: {
                        date: day
                    },
                    defaults: {
                        date: day,
                        type: info.type.type,
                        name: info.type.name,
                        timestamp: start
                    }
                })
                let holidayOne = holiday[0];
                holidayOne.timestamp = start;
                holidayOne.save();
            }

            start = start + 3600 * 24 * 1000;
        }
    }

    

    
}

module.exports = Tool;